package fileby.model.impl.sources.impl;

import fileby.model.impl.sources.FileItem;
import fileby.core.SourceType;
import fileby.core.IDisplayableFileSource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author Oscar
 */
public class FavoriteSource extends AbstractFileSource {

    private static FavoriteSource instance = null;

    private FavoriteSource() {
        updateContent();
    }

    public static FavoriteSource getInstance() {
        if (instance == null) {
            instance = new FavoriteSource();
        }
        return instance;
    }

    public IDisplayableFileSource getParent() {
        return null;
    }

    public boolean addFiles(List<File> fileList, int action) throws IOException {
        boolean update = false;
        for(File f : fileList) {
            boolean existsAlready = false;
            for (FileItem f2 : files) {
                if (f2.getFile().equals(f)) {
                    existsAlready = true;
                }
            }
            if (existsAlready == false) {
                update = true;
                files.add(new FileItem(f));
            }
        }
        writeToFile();
        return update;
    }

    public String getAbsolutePath() {
        return null;
    }

    public void removeFavorite(String path) {
        for (FileItem f : files) {
            if (f.getAbsolutePath().equals(path)) {
                files.remove(f);
                break;
            }
        }
        try {
            writeToFile();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void updateContent() {
        try {
            //read the favorite.txt and add it to the favoritelist.
            File favorites = new File("favorites.txt");

            if (favorites.exists()) {
                Scanner scan = new Scanner(favorites);

                while (scan.hasNext()) {
                    File fil = new File(scan.nextLine());
                    if (fil.exists()) {
                        files.add(new FileItem(fil));
                    }
                }
            }
        } catch (FileNotFoundException ex) {
        }
    }

    private void writeToFile() throws IOException {
        PrintWriter w = new PrintWriter(new BufferedWriter(new FileWriter("favorites.txt")));
        for (FileItem f : files) {
            w.write(f.getAbsolutePath() + "\n");
        }
        w.close();
    }

    @Override
    public SourceType getSourceType() {
        return SourceType.FAVORITE;
    }
}
